package com.qianye.aliyun.oss.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.qianye.aliyun.oss.AliyunApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: hjz
 * @DataTime: 2024/9/17 21:26
 **/
@Service
public class AliyunApiImpl implements AliyunApi {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    private OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    private static final Logger logger = LoggerFactory.getLogger(AliyunApiImpl.class);

    /**
     * 上传头像
     *
     * @param file
     * @throws IOException
     */
    @Override
    public String uploadAvatar(MultipartFile file) {

        //设置文件名称
        String fileName = String.valueOf(UUID.randomUUID().toString().replaceAll("-", ""));
        //获取文件后缀
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileUrl = "images/avatar/";
        String objectName = fileUrl + fileName + "." + fileSuffix;
        try {
            //上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        } catch (OSSException oe) {
            logger.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.error("Error Message:" + oe.getErrorMessage());
            logger.error("Error Code:" + oe.getErrorCode());
            logger.error("Request ID:" + oe.getRequestId());
            logger.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.error("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            logger.error("IOException");
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                logger.info("ossClient.shutdown()");
            }
        }
        return null;
    }

}
